//
//  OrderDetailViewController.m
//  LuxuryGoods
//
//  Created by DCQ on 2018/5/27.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "OrderDetailViewController.h"
#import "OrderAddressCell.h"
#import "OrderDetailNotifierCell.h"
#import "OrderGoodsImgCell.h"
#import "OrderGoodsInfoCell.h"
#import "OrderGoodsServiceCell.h"
#import "OrderInfoCell.h"
#import "LGImageManagerIO.h"
#import "OrderLogisticsViewController.h"
#import "UserInfoModel.h"
#import "OrderListModel.h"
#import "MyAddressListViewController.h"
#import "OrderNewAddressCell.h"
#import "RefoundDetailViewController.h"
#import "LGCommentViewController.h"
#import "LGRefundApplyVC.h"
#import "CustomerServiceViewController.h"

NSString *const  OrderAddressCellIdentifier = @"OrderAddressCellIdentifier";
NSString *const  OrderDetailNotifierCellIdentifier = @"OrderDetailNotifierCellIdentifier";
NSString *const  OrderGoodsImgCellIdentifier = @"OrderGoodsImgCellIdentifier";
NSString *const  OrderGoodsInfoCellIdentifier = @"OrderGoodsInfoCellIdentifier";
NSString *const  OrderGoodsServiceCellIdentifier = @"OrderGoodsServiceCellIdentifier";
NSString *const  OrderInfoCellIdentifier = @"OrderInfoCellIdentifier";
NSString *const  OrderNewAddressCellIdentifier = @"OrderNewAddressCellIdentifier";
@interface OrderDetailViewController ()
@property(nonatomic, copy) NSString * orderId;
@property(nonatomic, assign) OrderDetailStyle   style;
@property(nonatomic, strong) OrderDetailModel  * detailModel;
@end

@implementation OrderDetailViewController
- (instancetype)initWithStype:(OrderDetailStyle  )style withOrderId:(NSString *)order_id{
    self = [super init];
    if (self) {
        self.orderId = order_id;
        self.style = style;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString * titleStr = [self getTitleWithStyle:self.style];
    [self setNavigationItemTitle: titleStr];
  
    [self requestOrderDetail];
    
    if (self.style == OrderDetailStyle_waitComment||self.style == OrderDetailStyle_waitPayment|| self.style == OrderDetailStyle_waitGoods ) {
          [self setupBottomView];
    }
    
    if (self.style !=  OrderDetailStyle_cancel ||self.style != OrderDetailStyle_completeRefund ) {
         [self setupRightItem];
         
     }
    
}
- (NSString *)getTitleWithStyle:(NSInteger )style{
    NSString * stateStr = @"";
    //订单状态 0-待付款 10-待发货 20-待收货 30-待评价 40-已完成 50-退款中 51-退款被拒绝 60 -退款成功 90-已取消
    switch (style) {
        case 0:
            stateStr = @"待付款";
            
            break;
        case 10:
            stateStr = @"待发货";
            
            break;
        case 20:
            stateStr = @"待收货";
            
            break;
        case 30:
            stateStr = @"待评价";
            
            break;
        case 40:
            stateStr = @"已完成";
            
            break;
        case 50:
            stateStr = @"退款中";
            
            break;
        case 51:
            stateStr = @"退款被拒绝";
            
            break;
        case 60:
            stateStr = @"退款成功";
            
            break;
        case 90:
            stateStr = @"取消";
            
            break;
        default:
            break;
    }
    return stateStr;
}
- (void)requestOrderDetail{
    NSDictionary * params = @{@"order_id":self.orderId,@"token":UserInfo.userToken};
    WEAKSELF
    [[MainApi sharedInstance] postPath:@"/Order/detail" params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
        STRONGSELF
        NSLog(@"%@===",responseObject);
        if (responseObject && !error) {
            strongSelf.detailModel = [[OrderDetailModel alloc]initWithDictionary:responseObject error:nil];
            
        }
        [self setNavigationItemTitle: [strongSelf getTitleWithStyle:[strongSelf.detailModel.data.status integerValue]]];
        [strongSelf.tableView reloadData];
    }];
}

- (void)setupRightItem{
    
    NSString * barTitle = @"";
    if (self.style == OrderDetailStyle_waitPayment  ) {
        barTitle  =@"取消订单";
    }else if (self.style == OrderDetailStyle_waitSend||self.style == OrderDetailStyle_waitGoods||self.style == OrderDetailStyle_waitComment||self.style == OrderDetailStyle_complete){
        barTitle = @"申请退款";
    }else if (self.style == OrderDetailStyle_refundReview){
        barTitle = @"取消退款";
    }
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:barTitle forState:UIControlStateNormal];
    [rightBtn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)rightAction:(id)sender{
    if (self.style == OrderDetailStyle_waitPayment  ) {
//        barTitle  =@"取消订单";
        [self showAlertView:@"确定取消该订单吗?" withConfirmAction:^(UIAlertAction *action) {
            [self requestCancelOrder:@"90"];
        } withCancelAction:^(UIAlertAction *action) {
            
        }];
    }else if (self.style == OrderDetailStyle_waitSend||self.style == OrderDetailStyle_waitGoods||self.style == OrderDetailStyle_waitComment||self.style == OrderDetailStyle_complete){
//        barTitle = @"申请退款";
        [self gotoRefundApplyVC];
    }else if (self.style == OrderDetailStyle_refundReview){
//        barTitle = @"取消退款";
        
        [self showAlertView:@"确定取消该退款吗?" withConfirmAction:^(UIAlertAction *action) {
            [self requestCancelRefund];
        } withCancelAction:^(UIAlertAction *action) {
            
        }];
    }
    
}

//取消退款
- (void)requestCancelRefund{
    if (!self.detailModel.data.refund_id) {
        return ;
    }
    NSDictionary * params = @{@"refund_id":self.detailModel.data.refund_id,@"token":UserInfo.userToken};
 
    [[MainApi sharedInstance] postPath:@"/Order/cancelRefund" params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
      
        NSLog(@"%@===",responseObject);
        if (!error) {
            NSString *notificationName = @"";
            if (self.fromVCType == OrderDetailFromVCType_Msg) {
                notificationName = @"UPDATE_MESSAGE_LIST";
            }else{
                notificationName = @"UPDATE_ORDER_LIST";
            }
            
            [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil];
            [self backViewController];
        }
        
        
    }];
}
//取消订单
- (void)requestCancelOrder:(NSString *)status{
    NSDictionary * params = @{@"order_id":self.orderId,@"token":UserInfo.userToken,@"status":status};
 
    [[MainApi sharedInstance] postPath:@"/Order/confirmOrCancel" params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
        
        NSLog(@"%@===",responseObject);
        if (!error) {
            NSString *notificationName = @"";
           if (self.fromVCType == OrderDetailFromVCType_Msg) {
                notificationName = @"UPDATE_MESSAGE_LIST";
            }else{
                notificationName = @"UPDATE_ORDER_LIST";
            }
            
             [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil];
            [self backViewController];
        }
        
 
    }];
}
- (void)showAlertView:(NSString *)msg withConfirmAction:(void (^ __nullable)(UIAlertAction *action))confirmHandler withCancelAction:(void (^ __nullable)(UIAlertAction *action))cancelHandler{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"温馨提示"
                                                                   message:msg
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:confirmHandler];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:cancelHandler];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];

}
- (void)setupBottomView{
    CGFloat bottomHeight = 50;
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,  self.view.frame.size.height-bottomHeight, self.view.frame.size.width, bottomHeight)];
    [bottomView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:bottomView];
     NSString * btnTitle = @"立即支付";
    if (self.style == OrderDetailStyle_waitPayment ){
         btnTitle = @"立即支付";
    }else if (self.style == OrderDetailStyle_waitComment){
         btnTitle = @"立即评价";
    }else if ( self.style == OrderDetailStyle_waitGoods ){
        btnTitle = @"确认收货";
        
    }
   
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:btnTitle forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [btn addTarget:self action:@selector(btAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(20, 5, self.view.frame.size.width -40, bottomHeight- 10)];
    btn.layer.cornerRadius = (bottomHeight- 10)/2;
    btn.layer.masksToBounds =  YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [bottomView addSubview:btn];
    UIImage * bgImg = [LGImageManagerIO createGradualColorImage:btn.size startColor:UIColorFromRGB(0xE1CFA9) endColor:UIColorFromRGB(0xC1B284)];
     [btn setBackgroundImage:bgImg forState:UIControlStateNormal];
}

- (void)btAction:(id)sender{
     if ( self.style == OrderDetailStyle_waitGoods ){
         [self showAlertView:@"确定已经收到货了吗?" withConfirmAction:^(UIAlertAction *action) {
             [self requestCancelOrder:@"40"];
         } withCancelAction:^(UIAlertAction *action) {
             
         }];
     }else if (self.style == OrderDetailStyle_waitComment){
         
         [self gotoCommentVC];
     }else if (self.style == OrderDetailStyle_waitPayment){
         //支付
         
     }
    
}

- (CGRect)getTableViewFrame{
    
    CGFloat bottomHeight = 0;
    if (self.style == OrderDetailStyle_waitComment||self.style == OrderDetailStyle_waitPayment|| self.style == OrderDetailStyle_waitGoods ){
        bottomHeight = 50;
    }
    CGRect tableFrame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height -bottomHeight);
    return tableFrame;
}

- (void)registerCell{
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderAddressCell class]) bundle:nil] forCellReuseIdentifier:OrderAddressCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderDetailNotifierCell class]) bundle:nil] forCellReuseIdentifier:OrderDetailNotifierCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderGoodsImgCell  class]) bundle:nil] forCellReuseIdentifier:OrderGoodsImgCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderGoodsInfoCell class]) bundle:nil] forCellReuseIdentifier:OrderGoodsInfoCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderGoodsServiceCell  class]) bundle:nil] forCellReuseIdentifier:OrderGoodsServiceCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderInfoCell  class]) bundle:nil] forCellReuseIdentifier:OrderInfoCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderNewAddressCell  class]) bundle:nil] forCellReuseIdentifier:OrderNewAddressCellIdentifier];
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger section =  0;
    if (self.detailModel) {
        section = 3;
    }
    return section;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger row = 0;
    switch (section) {
        case 0:{
            if(self.style == OrderDetailStyle_waitGoods ||self.style == OrderDetailStyle_waitComment ||self.style == OrderDetailStyle_refundReview ||self.style ==OrderDetailStyle_completeRefund){
                row = 1;
                
            }else{
                row = 0;
            }
        }
            break;
        case 1:
            row = 1;
            break;
        case 2:
            row =  [self.detailModel.data.goods_item count] + 6;
            break;
            
        default:
            break;
    }
    
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if (indexPath.section == 0) {
        OrderDetailNotifierCell * tempCell = [tableView dequeueReusableCellWithIdentifier:OrderDetailNotifierCellIdentifier];
        DetailNotifierStyle style =  DetailNotifierStyle_noraml;
        NSString * logisticsName = @"";
        NSString * logisticsNo = @"";
        if (self.style == OrderDetailStyle_waitGoods|| self.style == OrderDetailStyle_waitComment) {
            style = DetailNotifierStyle_logistics;
            logisticsName = self.detailModel.data.express_name;
            logisticsNo = self.detailModel.data.express_no;
        }else if (self.style == OrderDetailStyle_refundReview){
             style = DetailNotifierStyle_refundAudit;
        }else if(self.style == OrderDetailStyle_completeRefund){
             style = DetailNotifierStyle_refund;
        }
        [tempCell  setupOrderDetail:style withLogisticsName:logisticsName withLogisticsNo:logisticsNo];
        tempCell.btnBlock = ^(DetailNotifierStyle style) {
            if (style == DetailNotifierStyle_logistics) {
                //物流
                [self gotoLogisticsVC];
            }else if (style == DetailNotifierStyle_refundAudit){
                //退款审核
                [self gotoRefundAuditVC];
            }else if (style == DetailNotifierStyle_refund){
                //退款成功
                [self gotoRefundCompleteVC];
            }
        };
        cell = tempCell;
    }else if (indexPath.section == 1){
        if (self.detailModel.data.address_tel) {
            OrderAddressCell * tempCell = [tableView dequeueReusableCellWithIdentifier:OrderAddressCellIdentifier];
            [tempCell setupADdressData:self.detailModel.data];
            cell = tempCell;
        }else{
            //添加地址
            OrderNewAddressCell * tempCell = [tableView dequeueReusableCellWithIdentifier:OrderNewAddressCellIdentifier];
            tempCell.addBlock = ^{
//                [self gotoOrderAddressVC];
            };
            cell = tempCell;
            
        }
      
    }else if (indexPath.section == 2){
        if (indexPath.row >= 0 && indexPath.row < [self.detailModel.data.goods_item count]) {
            OrderGoodsImgCell * tempCell = [tableView dequeueReusableCellWithIdentifier:OrderGoodsImgCellIdentifier];
            [tempCell setupADdressData:self.detailModel.data.goods_item[indexPath.row]];
            cell = tempCell;
        }else if (indexPath.row >=[self.detailModel.data.goods_item count] &&indexPath.row< [self.detailModel.data.goods_item count] + 4){
            
            OrderGoodsInfoCell * tempCell = [tableView dequeueReusableCellWithIdentifier:OrderGoodsInfoCellIdentifier];
            NSString * titleStr = @"";
            NSString * price = @"";
            if (indexPath.row == [self.detailModel.data.goods_item count]) {
                titleStr = @"商品金额";
                price =  [@"￥" stringByAppendingString:self.detailModel.data.all_total_price];
            }else if (indexPath.row == [self.detailModel.data.goods_item count] +1){
                titleStr = @"红包抵扣";
                 price =  [@"-￥" stringByAppendingString:self.detailModel.data.redpack_discount];
            }else if (indexPath.row == [self.detailModel.data.goods_item count] +2){
                titleStr = @"优惠券抵扣";
                 price =  [@"-￥" stringByAppendingString:self.detailModel.data.coupon_discount];
            }
            else if (indexPath.row == [self.detailModel.data.goods_item count] +3){
                titleStr = @"应付";
                 price =  [@"￥" stringByAppendingString:self.detailModel.data.pay_price];
            }
            [tempCell setupTitle:titleStr withPrice:price];
            cell = tempCell;
        }else if (indexPath.row == [self.detailModel.data.goods_item count] + 4){
            OrderGoodsServiceCell * tempCell = [tableView dequeueReusableCellWithIdentifier:OrderGoodsServiceCellIdentifier];
            tempCell.serviceBlock = ^{
              //联系客服
                [self gotoServiceVC];
            };
            cell = tempCell;
        }else if (indexPath.row == [self.detailModel.data.goods_item count] + 5){
            
            OrderInfoCell * tempCell =[tableView dequeueReusableCellWithIdentifier:OrderInfoCellIdentifier];
            [tempCell setupADdressData:self.detailModel.data withState:self.navigationItem.title];
            cell = tempCell;
        }
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 0;
    if (indexPath.section == 0) {
        height = 114;
    }else if (indexPath.section == 1){
        height = 100;
        
    }else if (indexPath.section == 2){
        
        if (indexPath.row >= 0 && indexPath.row < [self.detailModel.data.goods_item count]) {
            height = 95;
        }else if (indexPath.row >=[self.detailModel.data.goods_item count] &&indexPath.row< [self.detailModel.data.goods_item count] + 4){
            height = 40;
        }else if (indexPath.row == [self.detailModel.data.goods_item count] + 4){
           height = 76;
        }else if (indexPath.row == [self.detailModel.data.goods_item count] + 5){
            height = 80;
        }
        
        
    }
    
    return height;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = 0.001;
    if (section <3) {
        height = 10;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (self.style == OrderDetailStyle_waitGoods|| self.style == OrderDetailStyle_waitComment) {
            //物流
            [self gotoLogisticsVC];
        }else if (self.style == OrderDetailStyle_refundReview){
            //退款审核
            [self gotoRefundAuditVC];
        }else if (self.style == OrderDetailStyle_completeRefund){
            //退款成功
            [self gotoRefundCompleteVC];
        }
        
    }else if (indexPath.section == 1){
 
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)gotoOrderAddressVC{
    MyAddressListViewController  * addressListVC = [[MyAddressListViewController alloc]initWithStyle:AddressListVCStyle_changeOrderAddress];
    addressListVC.selectedBlock = ^(NSDictionary *addressDic) {
        NSString * address_id = addressDic[@"address_id"];
         NSString * consignee = addressDic[@"consignee"];
         NSString * phone = addressDic[@"phone"];
         NSString * location = addressDic[@"location"];
         NSString * detail_address = addressDic[@"detail_address"];
        
        self.detailModel.data.address = [location stringByAppendingString:detail_address];
        self.detailModel.data.address_tel = phone;
        self.detailModel.data.address_user = consignee;

        [self updateTableView];
    };
    [self pushViewController:addressListVC];
    
}

- (void)gotoLogisticsVC{
    OrderLogisticsViewController * logisticsVC = [[OrderLogisticsViewController alloc]initOrderId:self.orderId withVCType:LogisticsVCType_order];
    [self pushViewController:logisticsVC];
    
}
//申请退款 退款详情
- (void)gotoRefundAuditVC{
   
    [self refundDetailStyle:RefoundDetailVCStyle_apply];
}
//退款成功 退款详情
- (void)gotoRefundCompleteVC{
    [self refundDetailStyle:RefoundDetailVCStyle_complete];
}
- (void)refundDetailStyle:(RefoundDetailVCStyle )style{
    
    RefoundDetailViewController * detailVC = [[RefoundDetailViewController alloc]initWithOrderId:self.orderId withStyle:style withType:RefoundDetailVCType_order];
    if (self.fromVCType == OrderDetailFromVCType_Msg) {
        detailVC.fromVCType = RefoundDetailFromVCType_Msg;
    }
    [self pushViewController:detailVC];
}

- (void)gotoCommentVC{
    
    LGCommentViewController * commentVC = [[LGCommentViewController alloc]initWithOrderId:self.orderId withVCType:LGCommentVCType_order];
    if (self.fromVCType == OrderDetailFromVCType_Msg) {
        commentVC.fromVCType = CommentFromVCType_Msg;
    }
    [self pushViewController:commentVC];
}
//申请退款
- (void)gotoRefundApplyVC{
    LGRefundApplyVC * refundApplyVC = [[LGRefundApplyVC alloc]initWithOrderModel:self.detailModel.data];
    if (self.fromVCType == OrderDetailFromVCType_Msg) {
        refundApplyVC.fromVCType = RefundApplyFromVCType_Msg;
    }
    [self pushViewController:refundApplyVC];
}

//客服
- (void)gotoServiceVC{
    CustomerServiceViewController * tempVC = [[CustomerServiceViewController alloc]init];
    [self pushViewController:tempVC];
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
